package org.wejde.muel;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Iterator;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.muc.MultiUserChat;

/**
 * This class contains the JComponents and functions
 * related to the XMPP roster portion of the GUI.
 * 
 * The JComponents in this class are the JScrollPane and
 * JTextArea.
 * 
 * The methods include displaying the roster list in the
 * JTextArea.
 * 
 * This class implements the PacketLister interface so that
 * it can respond to presence-related XMPP packets.
 * 
 * @author Eric Martin
 * @author Webb Pinner
 *
 */
public class rosterPane extends JPanel implements PacketListener {

	/**
	 * The JTextArea for the roster names.
	 */
	private JTextArea roster;
	
	/**
	 * The JScrollPane to allow the roster JTextArea to
	 * scroll as needed.
	 */
	private JScrollPane rosterScroll;
	
	/**
	 * The MUC object to query for XMPP presence packets.
	 */
	private MultiUserChat muc;
	
	/**
	 * Serial Version UID
	 */
	private static final long serialVersionUID = 5154563530258558393L;

	/**
	 * Constructor method.
	 */
	public rosterPane() {
		this.setLayout(new BorderLayout());
		this.setMinimumSize(new Dimension(200, 545));
		this.setSize(this.getMinimumSize());
		
		this.roster = new JTextArea(30,15);
		this.roster.setEditable(false);
		this.roster.setLineWrap(false);
		this.rosterScroll = new JScrollPane(roster, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		this.add(rosterScroll);
		this.muc = null;
	}

	/**
	 * Process incoming XMPP presence-related packets.
	 * 
	 * @param packet
	 */
	public void processPacket(Packet packet) {
		if(this.muc != null) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.err.print("Updating Room Roster... ");
			roster.setText("");
			
			Iterator<String> occupants = this.muc.getOccupants();
			while (occupants.hasNext()) {
				String occupant = occupants.next();
				roster.append(occupant.split("/")[1] + "\n");
			}
			System.err.println("Success!");

			// DEBUG
			/**
			System.err.println("Number of room occupants: " + this.muc.getOccupantsCount());
			//occupants = this.muc.getOccupants();
			//while (occupants.hasNext()) {
			//	String occupant = occupants.next();
			//	System.err.println(occupant.split("/")[1]);
			}
			*/
		}
	}
	
	/**
	 * Set the Multi-User Chat object.
	 * 
	 * @param muc the muc object from the Smack API.
	 */
	public void setMUC(MultiUserChat muc) {
		this.muc = muc;
	}
	
	/**
	 * Method to update the XMPP roster.
	 */
	public void updateRoster() {
		processPacket(null);
	}
}
